// src/store/products.js
import { defineStore } from 'pinia'
import { getProducts } from '@/api/products' // 导入API请求函数

export const useProductStore = defineStore('products', {
  state: () => ({
    products: [],   
    isLoading: false, 
    error: null    
  }),

  actions: {
   
    async fetchProducts() {
      this.isLoading = true   // 开始加载
      this.error = null       // 清空旧错误
      try {
        const res = await getProducts() // 调用API层请求
        if (res.code === 200) {
          // 关键修改：处理商品图片路径，转换为Vite可识别的绝对路径
          this.products = res.data.map((product) => {
            let coverUrl = product.coverUrl || '' // 避免空值
            
           
            if (!coverUrl.startsWith('http')) {
             
              coverUrl = new URL(`../assets/${coverUrl}`, import.meta.url).href
            }
            
           
            return {
              ...product,
              coverUrl
            }
          })
        } else {
          this.error = res.msg    
        }
      } catch (err) {
        this.error = err.message || '网络请求失败' // 捕获异常
      } finally {
        this.isLoading = false // 结束加载
      }
    }
  }
})